<template>
	<view class="page-container" @click="handlePageTap">
		<!--智控台头部 -->
		<view class="header">
			<image class="my-dev header-item-center" src="../../assets/svg/dev.svg" @click="toDeviceList"></image>
			<view class="dev-name header-item-center" v-show="!BLEInfo.deviceId" @click="toDeviceList">姐钥仪</view>
			<view class="add-dev header-item-center" @click="addDevice" v-if="BLEInfo.status !== 3">
				添加设备
			</view>
			<view class="add-dev header-item-center" @click="openMask4" v-else>
				断开设备
			</view>
		</view>
		<!-- 设备连接状态 -->
		<view class="dev-status">
			<view v-if="BLEInfo.status == 3">已连接|<battery-display :battery="batteryValue" class="battery-box">
				</battery-display>{{batteryValue}}%</view>
			<view v-else>
				<!-- <battery-display battery="{{60}}" class="battery-box"></battery-display> -->
				设备未连接
			</view>
		</view>
		<!-- 语音 & 关机 -->
		<view class="my-card my-voice">
			<view class="jkey-btn-cancel voice-btn" @click="openMask5">
				<image src="../../assets/svg/voice.svg"></image>
				语音
			</view>
			<view class="jkey-btn-cancel voice-btn" @click="openMask3">
				<image src="../../assets/svg/close-dev.svg"></image>
				关机
			</view>
		</view>
		<!-- 模式选择 -->
		<view class="my-card my-mode">
			<view :class="(activedType == 1 ? 'jkey-btn-confirm' : 'jkey-btn-cancel') + ' mode-btn'" 
				@click="changeModeType(1)">医疗</view>
			<view :class="(activedType == 2 ? 'jkey-btn-confirm' : 'jkey-btn-cancel') + ' mode-btn'" 
				@click="changeModeType(2)">趣疗</view>
		</view>
		<block v-for="(modeList,index) in [[defaultMode1,selfMode1],[defaultMode2,selfMode2]]">
			<view class="my-card mode-box yiliao-box" v-show="activedType == [1,2][index]">
				<view class="mode-item"  
					:style="{backgroundColor:item.bgColor}" v-for="(item,i) in modeList[0]"
					
					>
					<view class="mode-icon">
						<image :src="item.icon"></image>
					</view>
					<view class="mode-name">{{item.name}}</view>
					<view class="mode-option" @click="modeAction(item.name)">
						<mode-option  :color="item.opColor" :show-action="activedName !== item.name">
						</mode-option>
					</view>
				</view>
				<!--自定义模式-->
				<view :class="'mode-item ' + (pressItemName == item.name ? 'mode-item-active' : '')"
					 @longpress.stop.="showModeOption(item.name)" 
					:style="{backgroundColor: item.bgColor}" v-for="(item,i) in modeList[1]">
					<view class="mode-icon self-mode">
						<view :style="'color:'+item.opColor + ';' + 'box-shadow: 0px 4px 10px 0px ' +item.opColor + ';'">
							{{item.name[item.name.length - 1]}}
						</view>
					</view>
					<view class="mode-name">{{item.name}}</view>
					<view class="mode-option" @click="modeAction(item.name)">
						<mode-option  :color="item.opColor" :showAction="activedName !== item.name">
						</mode-option>
					</view>
					<view class="option-mask">
						<view>
							<view hover-class="hover-btn" class="f-between" @click.stop="editMode">更改</view>
							<view hover-class="hover-btn" class="f-between" @click.stop="delMode">删除</view>
							<view hover-class="hover-btn" class="f-between" @click.stop="reNameMode">重命名</view>
						</view>
					</view>
				</view>
				<!-- 添加模式 -->
				<view class="mode-item" style="background-color: #C9E9F2;" @click="addMode" v-if="activedType == 2">
					<view class="mode-icon">
						<image src="../../assets/svg/mode/self.svg"></image>
					</view>
					<view class="mode-name">自定义</view>
					<view class="mode-option">
						<image style="width: 60rpx;height:60rpx;" src="../../assets/svg/mode/add.svg"></image>
					</view>
				</view>
			</view>
		</block> 
		<!-- 重命名模式 -->
		<view class="mask"  v-if="showMask1" style="z-index:999;">
		    <edit-mode-name :name="pressItemName" @namesave="namesave"></edit-mode-name>
		  </view>
		  <!-- 删除模式 -->
		  <view class="mask" v-if="showMask2" style="z-index:999;">
		    <del-pop @handledel="handleDel" :name="pressItemName">是否删除</del-pop>
		  </view>
		  <!-- 关机确认 -->
		  <view class="mask"  v-if="showMask3" style="z-index:999;">
		    <del-pop @handledel="powerOff" :name="pressItemName">{{maskTitle}}</del-pop>
		  </view>
		  <!-- 断开设备确认 -->
		  <view class="mask" v-if="showMask4" style="z-index:999;">
		    <del-pop @handledel="delDevice" :name="pressItemName">是否关闭设备连接</del-pop>
		  </view>
		   <!-- 语音 -->
		   <view class="mask" v-if="false" wx:if="{{showMask5}}" style="z-index:999;background-color: #ffffff00;">
<!-- 		    <voice-input bindclosevoice="handleCloseVoice" bindvoicestart="handleVoiceStart" bindvoiceend="handleVoiceEnd"></voice-input>
 -->		  </view>
		  <!-- 设备激活 -->
		 <!-- <view class="mask" v-if="false" wx:if="{{showMask6}}" style="z-index:999;">
		    <active-device bindclosemask="closeMask6"></active-device>
		  </view> -->
		  <!-- 未登录 -->
		  <view class="mask"  v-if="showMask7" style="z-index:500;background-color:rgba(0,0,0,0);" @click="showLoginToast">
		    
		  </view>
	</view>
	<my-tab-bar :active="1"></my-tab-bar>
</template>

<script>
	import {
		getDefaultMode,
		delMode,
		editModeName,
	} from '../../utils/jkeyMode'
	import {
		monitorBLE,
		queryBattery,
		powerOff,
		stopPump,
		delDevice,
		runMode
	} from '../../utils/bleController'
	export default {
		data() {
			return {
				activedName: '-1', //当前运行的模式名称
				isRunMode: false,
				activedType: 1, //当前模式类型1医疗 2趣疗
				defaultMode1: [], //医疗的默认模式
				defaultMode2: [], //趣疗的默认模式
				selfMode1: [], //医疗的自定义模式
				selfMode2: [], //趣疗的自定义模式

				BLEInfo: {}, //姐钥设备信息
				maskTitle: '', //打开pop的标题
				batteryValue: '', //电量
				pressItemName:'',
				showMask1:false,
				showMask2:false,
				showMask3:false,
				showMask4:false,
				showMask5:false,
				showMask6:false,
				showMask7:false,
				showMask8:false
			}
		},
		async onShow() {
			//window.vue3 = this
			//console.log('onShow',getApp())
			let defaultMode1 = await getDefaultMode(1)
			let defaultMode2 = await getDefaultMode(2)
			this.defaultMode1 = defaultMode1
			this.defaultMode2 = defaultMode2
			this.selfMode1 = uni.getStorageSync('selfModeList1') || []
			this.selfMode2 = uni.getStorageSync('selfModeList2') || []
			console.log(this.selfMode1,this.selfMode2)
			//获得蓝牙连接信息
			let BLEInfo = getApp().globalData.BLEInfo
			console.log('BLEINFO',BLEInfo)
			if (BLEInfo && BLEInfo.status == 3) {
				this.BLEInfo = BLEInfo
				monitorBLE((res) => {
					console.log('monitor',res)
					this.batteryValue = res
				})
				queryBattery()
			}
			//如果没有登录
			console.log('登录检测', uni.getStorageSync('isLogin'))
			if (!uni.getStorageSync('isLogin')) {
				return this.showMask7 = true
			}
			this.showMask7 = false
			//如果没有激活设备
			let info = uni.getStorageSync('loginInfo') || {}
			if (!info.doctor_id || info.doctor_id == 0) {
				this.showMask6 = true
			}
		},
		onHide() {
			this.handlePageTap()
		},
		onLoad(){
			//console.log('onLoad',getApp())
		},
		methods: {
			showLoginToast() {
				uni.showModal({
					cancelColor: 'cancelColor',
					title: '登录授权',
					content: '当前未登录，前往登录开启智控台',
					success(res) {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/login/login',
							})
						}
					}
				})
			},
			//模式被点击
			async modeAction(name) {
				//return console.log(name)
				let BLEInfo = getApp().globalData.BLEInfo ?? {}
				if (BLEInfo.status !== 3) {
					return uni.showToast({
						title: '设备未连接',
						icon: 'none'
					})
				}
				if (this.isRunMode && name !== this.activedName) {
					return uni.showToast({
						title: '当前有模式运行中，请关闭',
						icon: 'none'
					})
				} else if (name == this.activedName) {
					//暂停模式
					uni.showLoading({
						title: '操作中',
					})
					await stopPump()
					uni.hideLoading({
						success: (res) => {},
					})
					this.activedName = -1
					this.isRunMode = false
					return
				}

				let config
				for (let i of ['defaultMode', 'selfMode']) {
					//console.log(this[`${i}${this.activedType}`], `${i}${this.activedType}`)
					this[`${i}${this.activedType}`].some(x => {
						if (x.name == name) {
							config = x
							return true
						}
					})
				}
				console.log(config)
				//return 
				uni.setStorageSync('lastConfig', {
					activedType: this.activedType,
					config: config
				})
				this.activedName = name
				this.isRunMode = true
				console.log(config)
				await runMode(config)
				this.activedName = -1
				this.isRunMode = false
			},
			toDeviceList() {
				uni.navigateTo({
					url: '/pages/my-device/my-device',
				})
			},
			addDevice() {
				uni.navigateTo({
					url: '/pages/scan-device/scan-device',
				})
			},
			//切换模式类别
			changeModeType(type) {
				this.activedType = type
			},
			//添加模式
			addMode(e) {
				if (this[`selfMode${this.activedType}`].length >= 3) {
					return uni.showToast({
						title: '最多三个自定义模式',
						icon: 'none'
					})
				}
				uni.navigateTo({
					url: `/pages/mode/mode?type=${this.activedType}`,
				})
			},
			//项目长按
			showModeOption(name,otherName) {
				console.log('长按',name,otherName)
				this.pressItemName = name
			},
			//屏幕点击兜底，用于清除弹窗 一系列
			handlePageTap() {
				console.log('我触发了')
				this.pressItemName = -1
			},
			editMode() {
				uni.navigateTo({
					url: `/pages/mode/mode?type=${this.activedType}&name=${this.pressItemName}`,
				})
			},
			delMode() {
				this.showMask2 = true
				setTimeout(() => {
					this.pressItemName = -1
				})
			},
			reNameMode() {
				this.showMask1 = true
			},
			namesave(e) {
				//return console.log(e)
				let name = e.name
				let oldName = e.oldName
				let res = editModeName(this.activedType, oldName, name)
				if (!res.success) {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				} else {
					this['selfMode' + this.activedType] = uni.getStorageSync(`selfModeList${this.activedType}`),
					this.showMask1 = false
					uni.showToast({
						title: '修改成功',
						icon: 'none'
					})
				}
			},
			handleDel(e) {
				let confirm = e.confirm
				let name = e.name
				if (!confirm) {
					return this.showMask2 = false
				} else {
					let res = delMode(this.activedType, name)
					if (res.success) {
						uni.showToast({
							title: '删除成功',
							icon: 'none'
						})
						this['selfMode' + this.activedType] = uni.getStorageSync(`selfModeList${this.activedType}`)
						this.showMask2 = false
					}
				}
			},
			powerOff(e) {
				let confirm = e.confirm
				this.showMask3 = false
				if (confirm) {
					powerOff()
					this.BLEInfo = {}
					getApp().globalData.BLEInfo = {}
				}
			},
			openMask3() {
				if (this.BLEInfo.status !== 3) {
					return uni.showToast({
						title: '请连接设备',
						icon: 'none'
					})
				}
				this.maskTitle = '是否设备关机'
				this.showMask3 = true
			},
			openMask4() {
				console.log('关闭设备')
				this.showMask4 = true
			},
			delDevice(e) {
				//return console.log(e,'来自事件')
				let confirm = e.confirm
				this.showMask4 = false
				if (!confirm) {
					return
				}
				delDevice()
				this.BLEInfo = {}
				getApp().globalData.BLEInfo = {}
			},
			openMask5() {
				this.showMask5 = true
			},
			handleCloseVoice() {
				console.log('关闭')
				this.showMask5 = false
			},
			handleVoiceStart() {
				console.log('收到姐钥打开事件')
				if (this.isRunMode) {
					return uni.showToast({
						title: "有模式运行中",
						icon: "none"
					})
				}
				let list = [...this[`defaultMode${this.activedType}`], ...this[
					`selfMode${this.activedType}`]]
				let randomIndex = Math.floor(Math.random() * list.length)
				//构造参数
				let e = {
					currentTarget: {
						dataset: {
							name: list[randomIndex].name
						}
					}
				}
				console.log(list[randomIndex].name)
				this.modeAction(e)
			},
			handleVoiceEnd() {
				console.log('收到姐钥关闭事件')
				this.showMask5 = false
				this.openMask3()
				return
				if (this.data.onAction) {
					this.handleAction()
				} else {
					uni.showToast({
						title: '姐钥未开启',
						icon: 'error'
					})
				}
			},
			closeMask6() {
				console.log('关闭激活')
				uni.redirectTo({
					url: '/pages/index/index',
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
@import './index.css'
</style>
